package com.cxhc.common.utils;

import com.cxhc.common.config.QiniuConfig;
import com.cxhc.common.exception.file.FileNameLengthLimitExceededException;
import com.cxhc.common.exception.file.InvalidExtensionException;
import com.cxhc.common.utils.file.FileUploadUtils;
import com.cxhc.common.utils.file.MimeTypeUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.rmi.ServerException;
import java.util.Objects;

@Component
public class QiniuUtils {

    @Resource
    private QiniuConfig qiniuConfig;

    /**
     * 文件上传文件名最大长度
     */
    @Value("${file.defaultFileNameLength}")
    private Integer defaultFileNameLength;

    /**
     * 文件上传最大的大小
     */
    @Value("${file.defaultFileMaxSize}")
    private Integer defaultFileMaxSize;

    /**
     * 上传方法
     *
     * @param file
     * @return
     */
    public String scyGet(MultipartFile file, String key) throws ServerException {
        Configuration cfg = getConfiguration();
        // 其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // 文件名长度
        int fileNameLength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNameLength > defaultFileNameLength) {
            throw new FileNameLengthLimitExceededException(defaultFileNameLength);
        }
        // 文件校验 [全部文件]
        try {
            FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (InvalidExtensionException e) {
            throw new RuntimeException(e);
        }
        // 文件后缀名
        String extension = FileUploadUtils.getExtension(file);
        //文件原始名和随机数uuid拼接以防名字重复
        try {
            //byte[]数组方式读取文件；
            byte[] uploadBytes = file.getBytes();
            //读取
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            //申请七牛云成功后用户独有的两个识别符
            Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
            //资源存储的空间在七牛云中的空间
            String upToken = auth.uploadToken(qiniuConfig.getBucket());
            try {
                // 拼接文件名
                key = DateUtils.datePath() + "/" + key + "." + extension;
                System.out.println(" 文件名 = " + key);
                //上传七牛云                                              资源                    文件名  空间
                Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                //返回的文件名
                System.out.println("七牛云返回链接图片putRet.key =" + putRet.key);
                //返回内部名称
                System.out.println("七牛云返回链接图片putRet.hash=" + putRet.hash);
                response.close();
                byteInputStream.close();
                return qiniuConfig.getDomain() + "/" + putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                throw new ServerException(r.toString());
            }
        } catch (IOException e) {
            throw new ServerException("文件解析失败");
        }

    }


    public Configuration getConfiguration() {
        Configuration cfg = null;
        if (qiniuConfig.getStatus().equals("0")) {
            /*zone.zone0意思是华东*/
            cfg = new Configuration(Zone.zone0());
        } else if (qiniuConfig.getStatus().equals("1")) {
            /*zone.zone1华北*/
            cfg = new Configuration(Zone.zone1());
        } else if (qiniuConfig.getStatus().equals("2")) {
            /*zone.zone2华南*/
            cfg = new Configuration(Zone.zone2());
        }
        // 其他参数参考类注释
        return cfg;
    }


}
